﻿// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Web.Security;
using System.Web.UI.WebControls;
using BlueOnionSoftware.Bloget.Properties;

namespace BlueOnionSoftware.Bloget
{
    internal class EditUserView : View
    {
        private bool _disposed;
        private MembershipUser _user;
        private readonly TextBox _name = new TextBox();
        private readonly TextBox _displayName = new TextBox();
        private readonly TextBox _email = new TextBox();
        private readonly DropDownList _role = new DropDownList();
        private readonly TextBox _password = new TextBox();
        private readonly TextBox _password1 = new TextBox();
        private readonly TextBox _password2 = new TextBox();
        private readonly Button _editUser = new Button();
        private readonly Button _cancel = new Button();
        private readonly ConfirmedButton _remove = new ConfirmedButton();

        internal EditUserView(Bloget bloget)
            : base(bloget)
        {
            _name.ID = "name";
            _displayName.ID = "displayName";
            _role.ID = "role";
            _email.ID = "email";
            _password.ID = "password";
            _password1.ID = "password1";
            _password2.ID = "password2";
            _editUser.ID = "edit_user";
            _cancel.ID = "cancel";
            _remove.ID = "remove";
        }

        protected override string RootClassId()
        {
            return "edituser-view";
        }

        protected override void ShowView()
        {
            if (!Bloget.IsAdministrator)
            {
                var passwordForm = new PasswordView(Bloget);
                passwordForm.Show();
                return;
            }

            MainMenu.ShowMenu(Bloget);

            Bloget.WriteLine("<h3>" + Resources.EditUserViewHeader + "</h3>");

            var userName = Bloget.Page.Request[Bloget.BlogUserParameter];
            _user = Membership.GetUser(userName);

            if (_user == null)
            {
                Bloget.WriteLine(Resources.EditUserViewNoUserSpecified);
                return;
            }

            Bloget.WriteLine("<p>");

            Label(Resources.UsersViewNewUserName, _name.ID);
            _name.ReadOnly = true;
            RequiredTextBoxField(_name, _user.UserName, string.Empty);
            Bloget.WriteLine("<br/>");

            Label(Resources.EditUserViewDisplayName, _displayName.ID);
            RequiredTextBoxField(_displayName, _user.Comment, string.Empty);
            Bloget.WriteLine("<br/>");

            if (Bloget.IsAdministrator)
            {
                Label("Role", _role.ID);
                _role.Items.Add(new ListItem(Resources.EditUserViewRoleAuthor, Bloget.AdministratorRole));
                _role.Items.Add(new ListItem(Resources.EditUserViewRoleAdministrator, Bloget.AuthorRole));
                _role.SelectedIndex = Bloget.IsUserAdministrator(_user) ? 1 : 0;
                Bloget.Controls.Add(_role);
                Bloget.WriteLine("<br/>");
            }

            Label(Resources.UsersViewNewUserEmail, _email.ID);
            RequiredTextBoxField(_email, _user.Email, string.Empty);
            var emailValidator = AdminView.EmailValidator();
            emailValidator.ControlToValidate = _email.ID;
            Bloget.Controls.Add(emailValidator);
            Bloget.WriteLine("<br/>");

            Label(Resources.AdminViewOldPassword, _password.ID);
            PasswordField(_password);
            Bloget.WriteLine("<br/>");

            Label(Resources.UsersViewNewUserPassword, _password1.ID);
            PasswordField(_password1);
            var compareValidator = new CompareValidator
            {
                ControlToValidate = _password1.ID,
                ControlToCompare = _password2.ID,
                ErrorMessage = Resources.PasswordViewValidatorText
            };
            Bloget.Controls.Add(compareValidator);
            Bloget.WriteLine("<br/>");

            Label(Resources.UserViewNewUserConfirmPassword, _password2.ID);
            PasswordField(_password2);
            Bloget.WriteLine("</p>");

            Bloget.WriteLine("<p>");
            _editUser.Command += EditUserCommand;
            SubmitButton(_editUser, Resources.EditUserViewSubmit);

            Bloget.Write(" ");
            _cancel.Command += CancelCommand;
            _cancel.CausesValidation = false;
            SubmitButton(_cancel, "Cancel");

            if (Bloget.IsAdministrator && _user.UserName != Bloget.GetUser().UserName)
            {
                Bloget.Write(" ");
                _remove.Message = "Sure?";
                _remove.CausesValidation = false;
                _remove.Command += RemoveCommand;
                SubmitButton(_remove, "Remove");
            }

            Bloget.WriteLine("</p>");
        }

        private void RemoveCommand(object sender, CommandEventArgs e)
        {
            if (Bloget.IsAdministrator && _user.UserName != Bloget.GetUser().UserName)
            {
                Membership.DeleteUser(_user.UserName);
            }

            Log.EditUser(Bloget, _user.UserName, "Delete user");
            Bloget.Redirect(Bloget.BuildQueryString(Mode.Users));
        }

        private void CancelCommand(object sender, CommandEventArgs e)
        {
            Bloget.Redirect(Bloget.BuildQueryString(Mode.Users));
        }

        private void EditUserCommand(object sender, CommandEventArgs e)
        {
            if (Bloget.Page.IsValid)
            {
                try
                {
                    EditUser();
                }

                catch (Exception ex)
                {
                    Bloget.WriteLine(ex.Message);
                    return;
                }
            }
        }

        private void EditUser()
        {
            if (_user.Email != _email.Text ||
                _user.Comment != _displayName.Text)
            {
                _user.Email = _email.Text;
                _user.Comment = _displayName.Text;
                Membership.UpdateUser(_user);
                Log.EditUser(Bloget, _user.UserName, "Edit user setting");
            }

            if (string.IsNullOrEmpty(_password.Text) == false && string.IsNullOrEmpty(_password1.Text) == false)
            {
                var message = _user.ChangePassword(_password.Text, _password1.Text)
                    ? "Updated"
                    : "Failed";

                Log.EditUser(Bloget, _user.UserName, "Change password");
                Bloget.WriteLine(message);
            }
        }

        protected override void Dispose(bool managed)
        {
            try
            {
                if (_disposed == false)
                {
                    _disposed = true;

                    if (managed)
                    {
                        _name.Dispose();
                        _displayName.Dispose();
                        _role.Dispose();
                        _password.Dispose();
                        _password1.Dispose();
                        _password2.Dispose();
                        _email.Dispose();
                        _editUser.Dispose();
                        _cancel.Dispose();
                        _remove.Dispose();
                    }
                }
            }

            finally
            {
                base.Dispose(managed);
            }
        }
    }
}